package com.azdebugit.synchroniz.test;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {

    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock writeLock = readWriteLock.readLock();
    private static Lock readLock = readWriteLock.readLock();
    private int i;

    //读的方法
    public int ReadValue(Lock lock) throws Exception {
        try {
            lock.lock();
            Thread.sleep(1000);
            return i;
        } finally {
            lock.unlock();
        }
    }

    //写的方法
    public void setValue(Lock lock, int value) throws Exception {
        try {
            lock.lock();
            Thread.sleep(1000);
            i = value;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final ReadWriteLockDemo demo = new ReadWriteLockDemo();
        Runnable readRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(demo.ReadValue(readLock));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Runnable writeRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    demo.setValue(writeLock, new Random().nextInt());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        for (int i = 0; i < 20; i++) {
            new Thread(readRunnable).start();
        }
        for (int j = 0; j < 2; j++) {
            new Thread(writeRunnable).start();
        }
    }
}
